/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sum = 0;
    TreeNode* convertBST(TreeNode* root) {
        preOrderBST(root);
        updateBST(root);

        return root;
    }

    void preOrderBST(TreeNode* root) {
        if(root == nullptr) return;

        sum = sum + root->val;
        preOrderBST(root->left);
        preOrderBST(root->right);
    }

    void updateBST(TreeNode* root) {
        if(root == nullptr) return;
        
        updateBST(root->left);

        int temp = root->val;
        root->val = sum;
        sum = sum - temp;

        updateBST(root->right);
    }
};